package com.xianggu.demo;

import java.util.HashMap;
import java.util.Map;
/**
 * 统计字符串中字符出现的次数
 * @author xianggu
 * @date 2023-09-08
 */
public class CharacterCounter {
    public static Map<Character, Integer> countCharacters(String input) {
        Map<Character, Integer> charCountMap = new HashMap<>();
        if (input == null || input.isEmpty()) {
            return charCountMap;
        }
        
        // 转换为小写忽略大小写
        String lowerCaseInput = input.toLowerCase();

        for (int i = 0; i < lowerCaseInput.length(); i++) {
            char c = lowerCaseInput.charAt(i);
            // 只统计字母和数字，如需统计所有字符可去掉此判断
            if (Character.isLetterOrDigit(c)) {
                charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
            }
        }
        
        return charCountMap;
    }

    public static void main(String[] args) {
        String testStr = "HelloWorld!2023";
        Map<Character, Integer> result = countCharacters(testStr);
        System.out.println(result);
        // 输出: {!=1, r=1, d=1, e=1, w=1, h=1, l=3, o=2, 0=1, 2=2, 3=1}
    }
}